<?php
namespace Modules\Api\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Lib\upload;
use App\Models\Address;
use App\Models\Bill;
use App\Models\Goods;
use App\Models\GoodsColor;
use App\Models\GoodsSku;
use App\Models\Order;
use App\Models\OrderEvaluate;
use App\Models\OrderGoods;
use App\Models\Wxpay;
use App\Models\ShopCar;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Yansongda\Pay\Pay;

class OrderController extends Controller{

    //购物车生成订单
    public function orderAddApi(Request $request){
        try{
            $openid = $request->input("openid",false);
            $addressId = $request->input("address_id",false);
            $payMent = $request->input("payment",false);
            if (!$openid || !$addressId || !$payMent)return self::error(1000);
            $user = User::where("openid",$openid)->first();
            if (!$user)return self::error(1002);
            $address = Address::find($addressId);
            if (!$address)return self::error(1013);
            DB::beginTransaction();
            //生成订单号
            $orderSn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

            //查询购物车选中数据
            $shopcar = ShopCar::where("user_id",$user->id)->where("selected",1)->with("goods")->with("goodsSku")->with("goodsColor")->get();
            if ($shopcar->count()<1)return self::error(1015);
            $orderGoodsValue = [];
            $amount = 0;
            $goodsNum = 0;
            foreach ($shopcar as $item){
                if ($payMent=='wechat') {
                    $amount += $item["amount"] * $item['goods_num'];
                }else{
                    $amount += $item["score"] * $item['goods_num'];
                }
                $goodsNum += $item["goods_num"];
                $orderGoodsValue[] = ["order_sn"=>$orderSn,"order_id"=>0,"userid"=>$user->id,"goods_id"=>$item['goods']['id'],"goods_name"=>$item['goods']['goods_name'],"goods_image"=>$item['goods']["image"],"goods_price"=>$item['goods']['price'],"sku_score"=>$item["goodsSku"]["sku_score"],"sku_id"=>$item['goodsSku']['id'],"sku_name"=>$item['goodsSku']['sku_name'],"sku_price"=>$item['goodsSku']['sku_price'],"color_id"=>$item['goodsColor']["id"],"color_name"=>$item['goodsColor']['color_name'],"goods_num"=>$item["goods_num"],"goods_amount"=>$item["amount"],"created_at"=>Carbon::now()];
            }
            //生成订单
            $order = new Order();
            $order->order_sn = $orderSn;
            $order->userid = $user->id;
            $order->order_amount = $amount;
            $order->pay_amount = $amount;
            $order->payment = $payMent;
            $order->goods_num = $goodsNum;
            $order->username = $address->username;
            $order->phone = $address->phone;
            $order->address = $address->province.$address->city.$address->area.$address->detail;
            $order->order_status = 0;
            $order->order_time = Carbon::now();
            $order->created_at = Carbon::now();
            $order->save();
            //生成订单详情
            OrderGoods::insert($orderGoodsValue);
            //修改订单状态
            OrderGoods::where("order_sn",$orderSn)->update(["order_id"=>$order->id]);
            //删除购物车选中数据
            ShopCar::where("user_id",$user->id)->where("selected",1)->delete();
            if ($payMent=='integral'){
                //扣除用户积分
                if ($user->score < $amount)return self::error(1022);
                $user->score = $user->score-$amount;
                $user->save();
                //修改订单
                $order->order_status = 1;
                $order->pay_time = Carbon::now();
                $order->save();

                //记录消费
                $bill = new Bill();
                $bill->order_sn = $orderSn;
                $bill->userid = $user->id;
                $bill->money = $amount;
                $bill->type = 2;
                $bill->status = 1;
                $bill->save();

                //支付记录
                Wxpay::payMent($user->id,'integral',$orderSn,$amount,'order');
                DB::commit();
                return self::success();
            }elseif($payMent=='wechat'){
                //微信支付
                $pay = Wxpay::wxPay();
                $orderPay = [
                    'out_trade_no' => $orderSn,
                    'total_fee' => $amount*100, // **单位：分**
                    'body' => "微信快捷支付",
                    'openid' => $openid,
                ];
                $result = Pay::wechat($pay)->miniapp($orderPay);
                //支付记录
                Wxpay::payMent($user->id,'wechat',$orderSn,$amount,'order');
                //消费记录
                Bill::billAdd($orderSn,$user->id,$amount,2);
                DB::commit();
                return self::success($result);
            }else{
                return self::error(1016);
            }
        }catch (\Exception $e){
            Log::error($e);
            DB::rollback();
            return self::error(500);
        }
    }

    //立即购买
    public function orderBuyApi(Request $request){
        try{
            $openid = $request->input("openid",false);
            $addressId = $request->input("address_id",false);
            $goodsId = $request->input("goods_id",false);
            $skuId = $request->input("sku_id",false);
            $colorId = $request->input("color_id",false);
            $goodsNum = $request->input("goods_num",1);
            $payMent = $request->input("payment",false);
            if (!$openid || !$addressId || !$goodsId || !$skuId || !$colorId || !$payMent)return self::error(1000);

            $user = User::where("openid",$openid)->first();
            if (!$user)return self::error(1002);

            $goods = Goods::find($goodsId);
            $sku = GoodsSku::find($skuId);
            $color = GoodsColor::find($colorId);
            if (!$goods || !$sku || !$color)return self::error(1005);

            $address = Address::find($addressId);
            if (!$address)return self::error(1013);
            DB::beginTransaction();
            //生成订单号
            $orderSn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
            $amount = $sku->sku_price * $goodsNum;
            //生成订单
            $order = new Order();
            $order->order_sn = $orderSn;
            $order->userid = $user->id;
            $order->order_amount = $amount;
            $order->pay_amount = $amount;
            $order->payment = $payMent;
            $order->goods_num = $goodsNum;
            $order->username = $address->username;
            $order->phone = $address->phone;
            $order->address = $address->province.$address->city.$address->area.$address->detail;
            $order->order_status = 0;
            $order->order_time = Carbon::now();
            $order->created_at = Carbon::now();
            $order->save();

            //生成订单商品
            $orderGoods = new OrderGoods();
            $orderGoods->order_id = $order->id;
            $orderGoods->order_sn = $orderSn;
            $orderGoods->userid = $user->id;
            $orderGoods->goods_id = $goodsId;
            $orderGoods->goods_name = $goods->goods_name;
            $orderGoods->goods_image = $goods->image;
            $orderGoods->goods_price = $goods->price;
            $orderGoods->sku_id = $sku->id;
            $orderGoods->sku_name = $sku->sku_name;
            $orderGoods->sku_price = $sku->sku_price;
            $orderGoods->sku_score = $sku->sku_score;
            $orderGoods->color_id = $color->id;
            $orderGoods->color_name = $color->color_name;
            $orderGoods->goods_num = $goodsNum;
            $orderGoods->goods_amount = $amount;
            $orderGoods->created_at = Carbon::now();
            $orderGoods->save();

            if ($payMent=='integral'){
                //扣除用户积分
                if ($user->score < $amount)return self::error(1022);
                $user->score = $user->score-$amount;
                $user->save();
                //修改订单
                $order->payment = "integral";
                $order->order_status = 1;
                $order->pay_time = Carbon::now();
                $order->save();

                //记录消费
                $bill = new Bill();
                $bill->order_sn = $orderSn;
                $bill->userid = $user->id;
                $bill->money = $amount;
                $bill->type = 2;
                $bill->status = 1;
                $bill->save();

                //支付记录
                Wxpay::payMent($user->id,'integral',$orderSn,$amount,'order');
                DB::commit();
                return self::success();
            }elseif($payMent=='wechat'){
                //修改订单信息
                $order->payment = "wechat";
                $order->save();

                //微信支付
                $pay = Wxpay::wxPay();
                $orderPay = [
                    'out_trade_no' => $orderSn,
                    'total_fee' => $amount*100, // **单位：分**
                    'body' => "微信快捷支付",
                    'openid' => $openid,
                ];
                $result = Pay::wechat($pay)->miniapp($orderPay);
                //支付记录
                Wxpay::payMent($user->id,'wechat',$orderSn,$amount,'order');
                //消费记录
                Bill::billAdd($orderSn,$user->id,$amount,2);

                DB::commit();
                return self::success($result);
            }else{
                return self::error(1016);
            }

        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return self::error(500);
        }
    }

    //再次支付
    public function orderPayApi(Request $request){
        try{
            $orderId = $request->input("order_id",false);
            $payMent = $request->input("payment",false);
            if (!$orderId || !$payMent)return self::error(1000);
            $order = Order::find($orderId);
            if (!$order || $order->order_status!=0)return self::error(1020);
            $user = User::find($order->userid);
            if (!$user)return self::error(1003);
            if ($payMent=='integral'){
                //扣除用户积分
                if ($user->score < $order->pay_amount)return self::error(1022);
                $user->score = $user->score - $order->pay_amount;
                $user->save();
                //修改订单信息
                $order->payment = "integral";
                $order->order_status = 1;
                $order->pay_time = Carbon::now();
                $order->save();

                //支付记录
                Wxpay::where("pay_sn",$order->order_sn)->update(["is_paid"=>1,"paid_at"=>Carbon::now()]);
                return self::success();
            }elseif($payMent=='wechat'){
                //修改订单
                $order->payment = "wechat";
                $order->save();
                //微信支付
                $pay = Wxpay::wxPay();
                $orderPay = [
                    'out_trade_no' => $order->order_sn,
                    'total_fee' => $order->pay_amount*100, // **单位：分**
                    'body' => "微信快捷支付",
                    'openid' => $user->openid,
                ];
                $result = Pay::wechat($pay)->miniapp($orderPay);
                //支付记录
                Wxpay::where("pay_sn",$order->order_sn)->update(["is_paid"=>1,"paid_at"=>Carbon::now()]);
                return self::success($result);
            }else{
                return self::error(1016);
            }
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //订单列表
    public function orderListApi(Request $request){
        try{
            $openid = $request->input("openid",false);
            $status = $request->input("status",'all');
            $page = $request->input("page",1);
            $size = $request->input("size",20);
            if (!$openid)return self::error(1000);
            $user = User::where("openid",$openid)->first();
            if (!$user)return self::error(1002);
            if ($status=='all'){
                $query = Order::where("userid",$user->id);
                //查询订单
                $orderCount = $query->count();
                $orderData = $query->forPage($page,$size)->with('orderGoods')->orderBy("id","desc")->get();
            }else{
                $query = Order::query();
                $query = $query->where("userid",$user->id)->where("order_status",$status);
                $orderCount = $query->count();
                $orderData = $query->forPage($page,$size)->with('orderGoods')->orderBy("id","desc")->get();
            }
            if ($orderCount<1)return self::error(1003);
            return self::success(["count"=>$orderCount,"data"=>$orderData]);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //取消订单
    public function orderCloseApi(Request $request){
        try{
            $orderId = $request->input("order_id",false);
            if (!$orderId)return self::error(1000);
            $order = Order::find($orderId);
            if (!$order)return self::error(1020);
            if ($order->order_status!=0)return self::error(1021);
            $order->order_status = -1;
            $order->save();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //退款
    public function orderRefundApi(Request $request){
        try{
            $orderId = $request->input("order_id",false);
            if (!$orderId)return self::error(1000);
            $order = Order::find($orderId);
            if (!$order)return self::error(1020);
            if ($order->order_status<1)return self::error(1023);
            DB::beginTransaction();
            if ($order->payment = "integral"){
                //修改订单状态
                $order->order_status = 7;
                $order->refund_time = Carbon::now();
                $order->save();

                //增加用户积分
                $user = User::find($order->userid);
                $user->score = $user->score + $order->pay_amount;
                $user->save();

                //消费记录
                $bill = new Bill();
                $bill->order_sn = $order->order_sn;
                $bill->userid = $order->userid;
                $bill->money = $order->pay_amount;
                $bill->type = 1;
                $bill->status = 1;
                $bill->save();

                DB::commit();
                return self::success();
            }else{
                //查询支付信息
                $ment = Wxpay::where('order_sn',$order->order_sn)->where("userid",$order->userid)->first();
                if ($ment) {
                    $refund = Wxpay::refundPay();
                    //退款
                    $order = [
                        'transaction_id' => $$ment->transaction_id,
                        'out_refund_no' => $order->order_sn,
                        'total_fee' => $ment->amount*100, // **单位：分**
                        'refund_fee' => $ment->amount*100,
                        "type" => 'miniapp',
                        'refund_desc' => '微信支付退款'
                    ];
                    //调用支付
                    Pay::wechat($refund)->refund($order);
                }else{
                    return self::error(1024);
                }
            }
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return self::error(500);
        }
    }

    //确认收货
    public function orderConfirmReceipt(Request $request){
        try{
            $orderId = $request->input("order_id",false);
            if (!$orderId)return self::error(1000);
            $order = Order::find($orderId);
            if (!$order)return self::error(1020);
            if ($order->order_status!=2)return self::error(1025);
            $order->order_status = 3;
            $order->save();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //评价
    public function orderPingjia(Request $request){
        try{
            $orderId = $request->input("order_id",false);
            $content = $request->input("content",false);
            if (!$orderId || !$content)return self::error(1000);
            //查询订单
            $order = Order::find($orderId);
            if (!$order)return self::error(1020);
            if ($order->order_status!=3)return self::error(1027);
            DB::beginTransaction();
            //修改订单状态
            $order->order_status=4;
            $order->save();
            //查询订单商品
            $goods = OrderGoods::where("order_id",$order->id)->get();
            if ($goods->count()>0){
                foreach ($goods as $item){
                    $ping = new OrderEvaluate();
                    $ping->userid = $order->userid;
                    $ping->order_id = $order->id;
                    $ping->order_sn = $order->order_sn;
                    $ping->goods_id = $item['goods_id'];
                    $ping->content = $content;
                    $ping->created_at = Carbon::now();
                    $ping->save();
                }
            }
            DB::commit();
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return self::error(500);
        }
    }

    //评价图片
    public function orderPingjiaImage(Request $request){
        try{
            $orderId = $request->input("order_id",false);
            if (!$request->hasFile("files"))return self::error(1029);
            $file = upload::uploadOne("files");
            if (!$orderId || !$file)return self::error(1000);
            $order = Order::find($orderId);
            if (!$order)return self::error(1020);
            $ping = OrderEvaluate::where("order_id",$orderId)->get();
            if ($ping->count()<1)return self::error(1028);
            foreach ($ping as $item){
                if ($item['image']!='' && $item['image']!=null) {
                    $image = $item['image'].','.$file['data'];
                }else{
                    $image = $file['data'];
                }
                $item->image = $image;
                $item->save();
            }
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }
}
